// 配置对象
const config = {
    baseApiUrl: 'https://jsonplaceholder.typicode.com',
    method: 'GET'
};

/**
 * ajaxRequester.fetchData('/users/1')
 *             .then(data => {
 *                 // 处理成功的响应->成功为字符串(json格式的)
 *             })
 *             .catch(error => {
 *                 // 处理失败的响应->
 *             });
 */
class AjaxRequester {
    constructor(config) {
        if (AjaxRequester.instance) {
            return AjaxRequester.instance;
        }

        this.config = config;
        AjaxRequester.instance = this;

        // 其他私有方法...
    }

    fetchData(relativeUrl) {
        return new Promise((resolve, reject) => {
            let xhr;

            // 检查浏览器是否支持XMLHttpRequest
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }

            const fullUrl = `${this.config.baseApiUrl}${relativeUrl}`;
            xhr.open(this.config.method, fullUrl, true);
            xhr.responseType = 'json';

            xhr.onload = () => {
                if (xhr.status === 200) {
                    // 请求成功，解析响应并返回(这边是服务端的返回数据有问题)
                    resolve(xhr.response);
                } else {
                    // 请求失败，返回错误
                    reject('错误: ' + xhr.status);
                }
            };

            xhr.onerror = () => {
                reject('请求发生错误');
            };

            xhr.send();
        });
    }

    static getInstance(config) {
        if (!AjaxRequester.instance) {
            AjaxRequester.instance = new AjaxRequester(config);
        }
        return AjaxRequester.instance;
    }
}
